<template>
  <div class="">
    <h1>Login</h1>
    <div class="container">
      <mt-field label="用户名" placeholder="请输入用户名" v-model="loginForm.name"></mt-field>
      <mt-field label="密码" placeholder="请输入密码" type="password" v-model="loginForm.pass"></mt-field>
      <div></div>
    </div>
    <div class="split"></div>
    <div class="container">
      <mt-button type="primary" size="large" v-on:click.native="onSubmit">primary</mt-button>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
  import {loginUrl} from 'config/global.toml'

  export default {
    data() {
      return {
        loginForm: {
          name: '',
          pass: ''
        }
      }
    },
    methods: {
      onSubmit(formName) {
        this.login()
      },
      login() {
        //  登录
        let that = this
        this._remoteLogin({
          'username': that.loginForm.name,
          'password': that.loginForm.pass
        }).then(data => {
          if (data.success) {
            this.$KalixCatch.save('id', data.user.id)
            this.$KalixCatch.save('access_token', data.access_token)
            this.$KalixCatch.save('user_token', data.user.token)
            this.$KalixCatch.save('user_name', data.user.name)
            this.$KalixCatch.save('loginname', that.loginForm.name)
            // 在缓存中记录最后登录时间，处理单用户登录需求
            let now = new Date().getTime()
            this.$KalixCatch._saveLocal('lastLoginTime', now)
            this.$KalixCatch.save('lastLoginTime', now)
            this.$router.push({path: '/'})
          } else {
            this.$refs.loginFormName.focus()
            this.$KalixMessage.error(data.message)
          }
        }).catch(error => {
          console.log('login error ', error)
        })
      },
      /**
       * 登录函数
       * @param _data 传递的登录数据
       * @returns {Promise.<TResult>|*}
       */
      _remoteLogin(_data) {
        console.log(`remote address is ${loginUrl}`)
        return this.$http.request({
          method: 'POST',
          url: loginUrl,
          transformRequest: [(data) => {
            // Do whatever you want to transform the data
            let ret = ''
            for (let it in data) {
              ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
            }
            return ret
          }],
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          },
          data: _data
        }).then((res) => {
          console.log('[kalix]-[login.js] remoteLogin function return data is: ', res.data)
          return Promise.resolve(res.data)
        })
      }
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
</style>
